/**
 * Created by Administrator on 2015/12/1.
 */

var utils = require('utility')
var Page = require('../domain/domain').Page

module.exports = function (router) {

    /**
     * =========管理员登录页面========
     */
    router.get('/access/login', function *() {
        yield this.render('admin/login')
    })

    /**
     * ========管理员登录=========
     */
    router.post('/access/login', function *() {
        var body = this.request.body
        var username = body.username
        var password = body.password
        var admin = yield this.db('SELECT * FROM Admin WHERE username=? AND password=?', [username, password]).unique()
        if(!admin){
            yield this.render('admin/login', {
                title: '登录',
                username: username
            })
            return
        }
        this.session.admin = admin
        this.response.redirect('/admin/index')
    })

    /**
     * =======管理主页=========
     */
    router.get('/admin/index', function *() {
        yield this._render('admin/index', {
            title: '后台管理系统'
        })
    })

    /**
     * ========用户管理========
     */
    router.get('/admin/user', function *() {
        var pageNum = this.query.pageNum || 1
        var users = yield this.db('SELECT * FROM User LIMIT ?,?', [(pageNum-1)*20, 20]).list()
        yield this._render('admin/user', {
            title: '用户列表',
            users: users,
            dateformat: utils.YYYYMMDDHHmmss
        })
    })

    /**
     * =========菜谱管理==========
     */
    router.get('/admin/recipe', function *() {
        var pageNum = this.query.pageNum || 1
        var sqls = []
        sqls.push('SELECT R.*,U.nick AS owner_nick')
        sqls.push('FROM Recipe R, User U')
        sqls.push('WHERE R.owner_id=U.id LIMIT ?,?')
        var recipes = yield this.db(sqls.join(' '), [(pageNum-1)*5, 5]).list()
        var count = yield this.db('SELECT COUNT(*) FROM Recipe R, User U WHERE R.owner_id=U.id').count()
        var page = new Page(pageNum, 5, count, recipes)

        yield this._render('admin/recipes', {
            title: '菜谱列表',
            page: page,
            dateformat: utils.YYYYMMDDHHmmss
        })
    })

    /**
     * ==========菜单管理==========
     */
    router.get('/admin/menu', function *() {
        var pageNum = this.query.pageNum || 1
        var sqls = []
        sqls.push('SELECT M.*,U.nick AS owner_name,COUNT(*) AS recipe_count')
        sqls.push('FROM Menu M, User U, Recipe R, Recipe_Menu RM')
        sqls.push('WHERE M.user_id=U.id AND RM.m_id=M.id AND RM.r_id=R.id')
        sqls.push('GROUP BY M.id')
        sqls.push('LIMIT ?,?')
        var menus = yield this.db(sqls.join(' '), [(pageNum-1)*20, 20]).list()
        yield this._render('admin/menus', {
            title: '菜单列表',
            menus: menus,
            dateformat: utils.YYYYMMDDHHmmss
        })

    })

    /**
     * =========统计分析页面==========
     */
    router.get('/admin/statistics', function *() {
        yield this._render('admin/statistics', {
            title: '统计分析'
        })
    })

    /**
     * =========分类，思维导图========
     */
    router.get('/admin/statistics/plain/brain/category', function *() {
        var $self = this
        var categories = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id IS NULL').list()
        yield (function *(collects) {
            var callee = arguments.callee
            for(var i=0; i<collects.length; i++){
                var array = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id=?', collects[i].id).list()
                if(array.length > 0){
                    yield callee(array)
                    collects[i].children = array
                }
            }
        })(categories)
        console.log(JSON.stringify(categories))
        this.body = {
            code: 200,
            categories: categories
        }
    })

    /**
     * ==========统计分析，错落式片段===========
     */
    router.get('/admin/statistics/plain/partition/category', function *() {
        var $self = this
        var categories = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id IS NULL').list()
        yield (function *(collects) {
            var callee = arguments.callee
            for(var i=0; i<collects.length; i++){
                var array = yield $self.db('SELECT id,name FROM RecipeCtg WHERE parent_id=?', collects[i].id).list()
                if(array.length > 0){
                    yield callee(array)
                    collects[i].children = array
                    collects[i].size = array.reduce(function(pre, cur, index){
                        return index==1 ? pre.size + cur.size : pre + cur.size
                    })
                }
                var count = yield $self.db('SELECT COUNT(*) FROM Recipe WHERE category_id=?', collects[i].id).count()
                collects[i].size = collects[i].size ? collects[i].size + count : count == 0 ? 0.1 : count
            }
        })(categories)
        console.log(JSON.stringify(categories))
        this.body = {
            code: 200,
            categories: categories
        }
    })


    /**
     * ==========统计分析，每月菜谱发布条形图=========
     */
    router.get('/admin/statistics/plain/histogram/recipe', function*(){
        var year = new Date().getFullYear()
        var sqls = [
            'SELECT DATE_FORMAT(createOn, "%m") AS name, COUNT(*) AS value',
            'FROM Recipe',
            'WHERE DATE_FORMAT(createOn, "%Y")=?',
            'GROUP BY name'
        ]
        this.body = yield this.db(sqls.join(' '), year).list()
    })

    /**
     * ==========统计分析，每月菜单发布折线图=========
     */
    router.get('/admin/statistics/plain/line/menu', function*(){
        var year = new Date().getFullYear()
        var sqls = [
            'SELECT DATE_FORMAT(createOn, "%m") AS date, COUNT(*) AS value',
            'FROM Menu',
            'WHERE DATE_FORMAT(createOn, "%Y")=?',
            'GROUP BY date'
        ]
        this.body = yield this.db(sqls.join(' '), year).list()
    })

    /**
     * ==========统计分析，每月用户注册折线图=========
     */
    router.get('/admin/statistics/plain/line/user', function*(){
        var year = new Date().getFullYear()
        var sqls = [
            'SELECT DATE_FORMAT(createOn, "%m") AS date, COUNT(*) AS value',
            'FROM User',
            'WHERE DATE_FORMAT(createOn, "%Y")=?',
            'GROUP BY date'
        ]
        this.body = yield this.db(sqls.join(' '), year).list()
    })

    /**
     * ============统计分析，男女比例饼状图============
     */
    router.get('/admin/statistics/plain/pie/gender/scale', function *() {
        var sqls = [
            'SELECT gender, COUNT(*) AS count',
            'FROM User',
            'GROUP BY gender'
        ]
        var results = yield this.db(sqls.join(' ')).list()
        for(var i in results){
            if(results[i].gender){
                results[i].gender = '男'
            }else{
                results[i].gender = '女'
            }
        }
        this.body = results
    })





}